package cn.broadmax.boot.modules.sys.service.impl;

import cn.broadmax.boot.modules.sys.entity.SysUserRole;
import cn.broadmax.boot.modules.sys.mapper.SysUserRoleMapper;
import cn.broadmax.boot.modules.sys.service.ISysUserRoleService;
import cn.broadmax.boot.util.SAssert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jexx.util.CollectionUtil;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户角色 服务实现类
 * </p>
 *
 * @author jexx
 * @since 2021-05-13
 */
@Service
public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleMapper, SysUserRole> implements ISysUserRoleService {

    @Override
    public boolean appointRoleForUser(String userId, List<String> roleIds) {
        SAssert.notEmpty(roleIds, "roleIds not empty");
        List<SysUserRole> userRoles = getUserRolesByUserId(userId);

        List<String> removeIds = userRoles.stream().filter(s -> !roleIds.contains(s.getRoleId()))
                .map(SysUserRole::getId)
                .collect(Collectors.toList());
        if(CollectionUtil.isNotEmpty(removeIds)){
            super.removeByIds(removeIds);
        }

        List<String> existRoleIds = userRoles.stream().map(SysUserRole::getRoleId)
                .filter(roleIds::contains)
                .collect(Collectors.toList());

        List<SysUserRole> waitAddUserRoleList = new ArrayList<>();
        for(String roleId : roleIds){
            if(existRoleIds.contains(roleId)){
                continue;
            }
            SysUserRole sur = new SysUserRole();
            sur.setUserId(userId);
            sur.setRoleId(roleId);
            waitAddUserRoleList.add(sur);
        }
        if(CollectionUtil.isNotEmpty(waitAddUserRoleList)){
            super.saveBatch(waitAddUserRoleList);
        }
        return true;
    }

    @Override
    public List<SysUserRole> getUserRolesByUserId(String userId) {
        LambdaQueryWrapper<SysUserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUserRole::getUserId, userId);
        return super.list(wrapper);
    }
}
